/*
 *  Copyright 2020-2021 Li Fei
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.pengshun.modules.api.coal.service.impl;

import com.pengshun.modules.api.coal.domain.UserAddress;
import com.pengshun.modules.api.coal.service.dto.UserAddressDto;
import com.pengshun.modules.api.coal.util.SystemPath;
import com.pengshun.modules.api.mapper.SystemMapper;
import com.pengshun.modules.api.system.service.dto.AddresDto;
import com.pengshun.modules.common.BaseResult;
import com.pengshun.modules.common.UpdateUtil;
import lombok.RequiredArgsConstructor;
import com.pengshun.modules.api.coal.repository.UserAddressRepository;
import com.pengshun.modules.api.coal.service.UserAddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.MessageSource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * @author lifei
 * @date 2020-11-13
 **/
@Service
@RequiredArgsConstructor
public class UserAddressServiceImpl implements UserAddressService {

    private final UserAddressRepository userAddressRepository;
    private final MessageSource messageSource;
    private final SystemMapper systemMapper;
    private final RedisTemplate<String, String> redisTemplate;
    @Override
    public BaseResult queryAll(Long userId) {
        List<UserAddress> addresses = userAddressRepository.findByUserIdAndStatusOrderByCreateTimeDesc(userId, 1);
        return new BaseResult(0, addresses);
    }

    @Override
    @Transactional
    public BaseResult findById(Long id) {
        UserAddress userAddress = userAddressRepository.findById(id).orElseGet(UserAddress::new);
        return new BaseResult(0, userAddress);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult update(UserAddress resources) {
        UserAddress userAddress = userAddressRepository.findById(resources.getUserAddressId()).orElseGet(UserAddress::new);
//        userAddress.copy(resources);
        if (resources.getIsDefault() == 1) {
            //说明默认 修改其他为不默认
            List<UserAddress> addresses = userAddressRepository.findByUserId(resources.getUserId());
            for (UserAddress address : addresses) {
                address.setIsDefault(0);
            }
            userAddressRepository.saveAll(addresses);
        }
        BeanUtils.copyProperties(resources, userAddress, UpdateUtil.getNullPropertyNames(resources));
        userAddressRepository.save(userAddress);
        return new BaseResult(0, messageSource.getMessage("update.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult defaultAddress(Long id) {
        UserAddress addresses = userAddressRepository.findByUserIdAndIsDefaultAndStatus(id, 1, 1);
        return new BaseResult(0, addresses);
    }

    @Override
    public BaseResult save(UserAddress address) {
        AddresDto city = systemMapper.selectBysdId(address.getSdId());
        address.setSpId(city.getProvinceId());
        address.setScId(city.getCityId());
        if (address.getIsDefault() == 1) {
            //说明默认 修改其他为不默认
            List<UserAddress> addresses = userAddressRepository.findByUserId(address.getUserId());
            for (UserAddress add : addresses) {
                add.setIsDefault(0);
            }
            userAddressRepository.saveAll(addresses);
        }
        userAddressRepository.save(address);
        return new BaseResult(0, messageSource.getMessage("save.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult delete(UserAddress address) {
        UserAddress userAddress = userAddressRepository.findById(address.getUserAddressId()).orElse(null);
        if (userAddress != null) {
            userAddress.setStatus(2);
            userAddressRepository.save(userAddress);
        }
        return new BaseResult(0, messageSource.getMessage("delete.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult selectHistoryCity(Long id) {

        String code = (String) redisTemplate.boundValueOps(SystemPath.APP_LOGIN_CODE_PATH + id).get();

        return null;
    }

    @Override
    public BaseResult saveHistoryCity(UserAddressDto para) {
        //先查询  在追加 在保存
        redisTemplate.boundValueOps(SystemPath.APP_CITY_HISTORY_PATH + para.getUserId()).set(para.getAddress());
        return new BaseResult(0);
    }

    @Override
    public BaseResult delHistoryCity(Long id) {
        redisTemplate.delete(SystemPath.APP_CITY_HISTORY_PATH + id);
        return new BaseResult(0);
    }
}